package me.winds.infrared.utils;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;

import com.easyder.wrapper.utils.LogUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.winds.infrared.R;
import me.winds.infrared.AppConfig;
import me.winds.infrared.WrapperApplication;
import me.winds.infrared.utils.algorithms.BilineInterpolationScale;
import me.winds.widget.usage.ToastView;

/**
 * Author:  winds
 * Data:    2018/8/24
 * Version: 1.0
 * Desc:
 */


public class InfraredUtils {

    /**
     * 保存Bitmap到sdcard
     *
     * @param bitmap
     */
    public static String saveImage(Bitmap bitmap) {
        String path = AppConfig.DEFAULT_IMAGE_PATH;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        long dataTake = System.currentTimeMillis();
        String filepath = path + File.separator + dataTake + ".jpeg";
        try {
            FileOutputStream fos = new FileOutputStream(filepath);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            return filepath;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    private static String initPath() {
        String storagePath = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                storagePath = AppConfig.DEFAULT_IMAGE_PATH;
            } else {
                storagePath = WrapperApplication.getInstance().getCacheDir().getPath();
            }
        } catch (Exception e) {
            storagePath = WrapperApplication.getInstance().getCacheDir().getPath();
        } finally {
            File file = new File(storagePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        return storagePath;
    }

    /**
     * 数据保存成图片
     * @param imageBuffer
     * @param centerTemp
     * @param showCenter
     */
    public static void takePicture(int[] imageBuffer, final double centerTemp, final boolean showCenter) {
        Observable.just(imageBuffer)
                .map(new Function<int[], int[]>() {
                    @Override
                    public int[] apply(int[] ints) throws Exception {
                        LogUtils.info("--> takePicture start " + System.currentTimeMillis());
                        return BilineInterpolationScale.imgScale(ints, AppConfig.SIZE_WIDTH, AppConfig.SIZE_HEIGHT, AppConfig.SIZE_WIDTH * 3, AppConfig.SIZE_HEIGHT * 3);
                    }
                })
                .map(new Function<int[], Bitmap>() {
                    @Override
                    public Bitmap apply(int[] ints) throws Exception {
                        return Bitmap.createBitmap(ints, 0, AppConfig.SIZE_WIDTH * 3, AppConfig.SIZE_WIDTH * 3, AppConfig.SIZE_HEIGHT * 3, Bitmap.Config.RGB_565);
                    }
                })
                .map(new Function<Bitmap, Bitmap>() {
                    @Override
                    public Bitmap apply(Bitmap bitmap) throws Exception {
                        if (showCenter) {
                            return drawTextToLeftTop(bitmap, String.format("%1$.2f%2$s", centerTemp, "℃"), 18, Color.WHITE, 20, 10);
                        }
                        return bitmap;
                    }
                })
                .map(new Function<Bitmap, Bitmap>() {
                    @Override
                    public Bitmap apply(Bitmap bitmap) throws Exception {
                        if (showCenter) {
                            Bitmap resource = BitmapFactory.decodeResource(WrapperApplication.getInstance().getResources(), R.drawable.ic_cursor_write);
                            return createWaterMaskBitmap(bitmap, resource,
                                    AppConfig.SIZE_WIDTH * 3 / 2 - resource.getWidth() / 2, AppConfig.SIZE_HEIGHT * 3 / 2 - resource.getHeight() / 2);
                        }
                        return bitmap;
                    }
                })
                .map(new Function<Bitmap, SoftReference<Bitmap>>() {
                    @Override
                    public SoftReference<Bitmap> apply(Bitmap bitmap) throws Exception {
                        return new SoftReference<>(bitmap);
                    }
                })
                .map(new Function<SoftReference<Bitmap>, String>() {
                    @Override
                    public String apply(SoftReference<Bitmap> bitmapSoftReference) throws Exception {
                        if (bitmapSoftReference != null) {
                            Bitmap bitmap = bitmapSoftReference.get();
                            if (bitmap != null) {
                                return InfraredUtils.saveImage(bitmap);
                            }
                        }
                        return "";
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        LogUtils.info("--> takePicture end " + System.currentTimeMillis());
                        if (!TextUtils.isEmpty(s)) {
                            try {
                                File file = new File(s);
                                MediaStore.Images.Media.insertImage(WrapperApplication.getInstance().getContentResolver(),
                                        file.getAbsolutePath(), file.getName(), null);
                                WrapperApplication.getInstance().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                        Uri.fromFile(file)));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            LogUtils.info("图片保存在" + s);
//                            showToast("图片保存在" + s);
                        } else {
                            showToast("保存失败");
                        }
                    }
                });
    }

    /**
     * 生成水印
     * @param src
     * @param watermark
     * @param paddingLeft
     * @param paddingTop
     * @return
     */
    public static Bitmap createWaterMaskBitmap(Bitmap src, Bitmap watermark,
                                               int paddingLeft, int paddingTop) {
        int width = src.getWidth();
        int height = src.getHeight();
        //创建一个bitmap
        Bitmap newb = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);// 创建一个新的和SRC长度宽度一样的位图
        //将该图片作为画布
        Canvas canvas = new Canvas(newb);
        //在画布 0，0坐标上开始绘制原始图片
        canvas.drawBitmap(src, 0, 0, null);
        //在画布上绘制水印图片
        canvas.drawBitmap(watermark, paddingLeft, paddingTop, null);
        // 保存
        canvas.save(Canvas.ALL_SAVE_FLAG);
        // 存储
        canvas.restore();
        return newb;
    }

    /**
     * 给图片添加文字到左上角
     *
     * @param bitmap
     * @param text
     * @return
     */
    public static Bitmap drawTextToLeftTop(Bitmap bitmap, String text,
                                           int size, int color, int paddingLeft, int paddingTop) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(color);
        paint.setTextSize(size);
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return drawTextToBitmap(bitmap, text, paint, paddingLeft, paddingTop + bounds.height());
    }

    //图片上绘制文字
    private static Bitmap drawTextToBitmap(Bitmap bitmap, String text,
                                           Paint paint, int paddingLeft, int paddingTop) {
        Bitmap.Config config = bitmap.getConfig();
        paint.setDither(true); // 获取跟清晰的图像采样
        paint.setFilterBitmap(true);// 过滤一些
        if (config == null) {
            config = android.graphics.Bitmap.Config.RGB_565;
        }
        bitmap = bitmap.copy(config, true);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawText(text, paddingLeft, paddingTop, paint);
        return bitmap;
    }

    protected static void showToast(String msg) {
        ToastView.showToastInCenter(WrapperApplication.getInstance(), msg, Toast.LENGTH_SHORT);
    }
}
